package com.note.simpleshop.module.user.service;
import com.note.simpleshop.entity.TbAddress;
import com.note.simpleshop.exception.NotDataException;
import com.note.simpleshop.module.user.dao.AddressRepository;
import com.note.simpleshop.utils.IdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressService {
    private static final Logger logger = LoggerFactory.getLogger(AddressService.class);
    @Autowired
    private AddressRepository addressRepository;
    public List<TbAddress> findByUserIdAndIsDelete(String userId, Integer isDelete) {
        return addressRepository.findByUserIdAndIsDelete(userId, isDelete);
    }
    public List<TbAddress> findByUserId(String userId) {
        return addressRepository.findByUserIdAndIsDelete(userId, TbAddress.IS_DELEETE0);
    }
    public TbAddress findByIdAndUserId(String id, String userId) {
        return addressRepository.findByIdAndUserIdAndIsDelete(id, userId, TbAddress.IS_DELEETE0);
    }
    public String save(TbAddress tbAddress) {
        String addressId=IdGenerator.id();
        tbAddress.setId(addressId);
        tbAddress.setIsUse(TbAddress.IS_USE0);
        tbAddress.setIsDelete(TbAddress.IS_DELEETE0);
        addressRepository.save(tbAddress);
        return addressId;
    }
    public void updateIsUse(String id,String userId,Integer isUse) throws NotDataException
    {
        TbAddress tbAddress=findByIdAndUserId(id,userId);
        if(tbAddress==null)
        {
            throw new NotDataException("地址信息不存在");
        }
        addressRepository.updateIsUse(TbAddress.IS_USE0,userId);
        tbAddress.setIsUse(isUse);
        addressRepository.save(tbAddress);
    }
    public void update(TbAddress model) throws NotDataException{
        TbAddress tbAddress=findByIdAndUserId(model.getId(),model.getUserId());
        if(tbAddress==null)
        {
            throw new NotDataException("address信息不存在");
        }
        model.setIsUse(tbAddress.getIsUse());
        model.setIsDelete(tbAddress.getIsDelete());
        addressRepository.save(model);
    }
    public void delete(String id,String userId) throws NotDataException
    {
        TbAddress tbAddress=findByIdAndUserId(id,userId);
        if(tbAddress==null)
        {
            throw new NotDataException("address信息不存在");
        }
        tbAddress.setIsDelete(TbAddress.IS_DELETE1);
        addressRepository.save(tbAddress);
    }


}